package net.huanger.gametools.mapeditor.ui;


import static net.huanger.gametools.mapeditor.ui.MUtils.MAP_UNIT;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JComponent;


public class TitePicCanvas extends JComponent
{
  private static final long serialVersionUID = 1L;

  private int row = -1, column = -1;

  private MapEditorPanel mapEditorPanel;

  public static BufferedImage image;

  private Point selectPoint;

  public TitePicCanvas(MapEditorPanel mapEditorPanel)
  {
    this.mapEditorPanel = mapEditorPanel;
    initEventListener();
  }

  private void initEventListener()
  {
    this.addMouseListener(new MouseAdapter()
      {

        @Override
        public void mouseClicked(MouseEvent e)
        {
          OperateContext oc = mapEditorPanel.getOperateContext();
          if (oc != null)
          {
            oc.titeClick(e, row, column);
          }
        }
      });
  }

  @Override
  protected void paintComponent(Graphics g)
  {
    //    super.paintComponent(g);
    g.drawImage(image, 0, 0, column * MAP_UNIT, row * MAP_UNIT, 0, 0, column * MAP_UNIT, row * MAP_UNIT, null);
    
    //画选中边框
    if (selectPoint != null)
    {
      Color old = g.getColor();
      g.setColor(Color.red);
      g.drawRect(selectPoint.x, selectPoint.y, MAP_UNIT, MAP_UNIT);
      g.setColor(old);
    }
  }

  public void importTitePic(File file) throws IOException
  {
    image = ImageIO.read(file);
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    this.column = width / MAP_UNIT;
    this.row = height / MAP_UNIT;
    width = column * MAP_UNIT;
    height = row * MAP_UNIT;
    Dimension preferredSize = new Dimension(width, height);
    this.setPreferredSize(preferredSize);
    mapEditorPanel.setDiv(width + 5);
  }

  public BufferedImage getTiteImage()
  {
    return image;
  }

  public void repaint(Point old, Point titePoint)
  {
    this.repaint(old.x, old.y, MUtils.MAP_UNIT + 1, MUtils.MAP_UNIT + 1);
    this.selectPoint = titePoint;
    this.repaint(titePoint.x, titePoint.y, MUtils.MAP_UNIT + 1, MUtils.MAP_UNIT + 1);
  }

  public int getRow()
  {
    return this.row;
  }

  public int getColumn()
  {
    return this.column;
  }
}
